#!/bin/bash

# WalkerRadio 一键部署脚本
# 支持 Docker 和传统部署方式

set -e

echo "🏔️ WalkerRadio 户外电波 - 一键部署脚本 🏔️"
echo "================================================"

# 检查系统要求
check_requirements() {
    echo "📋 检查系统要求..."
    
    # 检查操作系统
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        echo "✅ 操作系统: Linux"
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        echo "✅ 操作系统: macOS"
    else
        echo "❌ 不支持的操作系统: $OSTYPE"
        exit 1
    fi
    
    # 检查 Docker
    if command -v docker &> /dev/null; then
        echo "✅ Docker 已安装: $(docker --version)"
    else
        echo "❌ Docker 未安装，请先安装 Docker"
        echo "安装指南: https://docs.docker.com/get-docker/"
        exit 1
    fi
    
    # 检查 Docker Compose
    if command -v docker-compose &> /dev/null; then
        echo "✅ Docker Compose 已安装: $(docker-compose --version)"
    else
        echo "❌ Docker Compose 未安装，请先安装 Docker Compose"
        exit 1
    fi
}

# 选择部署方式
select_deployment_method() {
    echo ""
    echo "🚀 请选择部署方式:"
    echo "1) Docker 部署 (推荐)"
    echo "2) 传统部署"
    echo "3) 仅构建项目"
    echo ""
    read -p "请输入选择 (1-3): " choice
    
    case $choice in
        1)
            deploy_with_docker
            ;;
        2)
            deploy_traditional
            ;;
        3)
            build_only
            ;;
        *)
            echo "❌ 无效选择，请重新运行脚本"
            exit 1
            ;;
    esac
}

# Docker 部署
deploy_with_docker() {
    echo ""
    echo "🐳 开始 Docker 部署..."
    
    # 检查端口占用
    if lsof -Pi :80 -sTCP:LISTEN -t >/dev/null 2>&1; then
        echo "⚠️  端口 80 已被占用，请先停止占用该端口的服务"
        read -p "是否继续？(y/N): " continue_deploy
        if [[ $continue_deploy != "y" && $continue_deploy != "Y" ]]; then
            exit 1
        fi
    fi
    
    if lsof -Pi :5000 -sTCP:LISTEN -t >/dev/null 2>&1; then
        echo "⚠️  端口 5000 已被占用，请先停止占用该端口的服务"
        read -p "是否继续？(y/N): " continue_deploy
        if [[ $continue_deploy != "y" && $continue_deploy != "Y" ]]; then
            exit 1
        fi
    fi
    
    # 构建前端
    echo "📦 构建前端应用..."
    cd walkerradio-frontend
    if command -v pnpm &> /dev/null; then
        pnpm install
        pnpm run build
    elif command -v npm &> /dev/null; then
        npm install
        npm run build
    else
        echo "❌ 未找到 npm 或 pnpm，请先安装 Node.js"
        exit 1
    fi
    cd ..
    
    # 启动 Docker 服务
    echo "🚀 启动 Docker 服务..."
    docker-compose down 2>/dev/null || true
    docker-compose up -d --build
    
    # 等待服务启动
    echo "⏳ 等待服务启动..."
    sleep 10
    
    # 检查服务状态
    if docker-compose ps | grep -q "Up"; then
        echo ""
        echo "🎉 部署成功！"
        echo "📱 前端访问地址: http://localhost"
        echo "🔧 后端API地址: http://localhost:5000"
        echo "📊 查看服务状态: docker-compose ps"
        echo "📋 查看日志: docker-compose logs -f"
        echo "🛑 停止服务: docker-compose down"
    else
        echo "❌ 部署失败，请查看日志: docker-compose logs"
        exit 1
    fi
}

# 传统部署
deploy_traditional() {
    echo ""
    echo "🔧 开始传统部署..."
    
    # 检查 Python
    if ! command -v python3 &> /dev/null; then
        echo "❌ Python3 未安装，请先安装 Python 3.11+"
        exit 1
    fi
    
    # 检查 Node.js
    if ! command -v node &> /dev/null; then
        echo "❌ Node.js 未安装，请先安装 Node.js 18+"
        exit 1
    fi
    
    # 部署后端
    echo "🐍 部署后端服务..."
    cd walkerradio_backend
    
    if [ ! -d "venv" ]; then
        python3 -m venv venv
    fi
    
    source venv/bin/activate
    pip install -r requirements.txt
    pip install gunicorn
    
    # 启动后端服务
    echo "🚀 启动后端服务..."
    nohup ./start_production.sh > ../backend.log 2>&1 &
    BACKEND_PID=$!
    echo $BACKEND_PID > ../backend.pid
    
    cd ..
    
    # 部署前端
    echo "⚛️  部署前端应用..."
    cd walkerradio-frontend
    
    if command -v pnpm &> /dev/null; then
        pnpm install
        pnpm run build
    else
        npm install
        npm run build
    fi
    
    # 启动前端服务
    echo "🚀 启动前端服务..."
    if command -v pnpm &> /dev/null; then
        nohup pnpm run preview --host --port 80 > ../frontend.log 2>&1 &
    else
        nohup npm run preview -- --host --port 80 > ../frontend.log 2>&1 &
    fi
    FRONTEND_PID=$!
    echo $FRONTEND_PID > ../frontend.pid
    
    cd ..
    
    # 等待服务启动
    echo "⏳ 等待服务启动..."
    sleep 5
    
    echo ""
    echo "🎉 部署成功！"
    echo "📱 前端访问地址: http://localhost"
    echo "🔧 后端API地址: http://localhost:5000"
    echo "📋 查看后端日志: tail -f backend.log"
    echo "📋 查看前端日志: tail -f frontend.log"
    echo "🛑 停止服务: ./stop_services.sh"
    
    # 创建停止脚本
    cat > stop_services.sh << 'EOF'
#!/bin/bash
echo "🛑 停止 WalkerRadio 服务..."

if [ -f backend.pid ]; then
    kill $(cat backend.pid) 2>/dev/null || true
    rm backend.pid
    echo "✅ 后端服务已停止"
fi

if [ -f frontend.pid ]; then
    kill $(cat frontend.pid) 2>/dev/null || true
    rm frontend.pid
    echo "✅ 前端服务已停止"
fi

echo "🎉 所有服务已停止"
EOF
    chmod +x stop_services.sh
}

# 仅构建项目
build_only() {
    echo ""
    echo "📦 仅构建项目..."
    
    # 构建前端
    echo "⚛️  构建前端..."
    cd walkerradio-frontend
    if command -v pnpm &> /dev/null; then
        pnpm install
        pnpm run build
    else
        npm install
        npm run build
    fi
    cd ..
    
    # 准备后端
    echo "🐍 准备后端..."
    cd walkerradio_backend
    if [ ! -d "venv" ]; then
        python3 -m venv venv
    fi
    source venv/bin/activate
    pip install -r requirements.txt
    cd ..
    
    echo ""
    echo "🎉 构建完成！"
    echo "📁 前端构建文件: walkerradio-frontend/dist/"
    echo "📁 后端源码: walkerradio_backend/"
    echo "📖 部署指南: DEPLOYMENT_GUIDE.md"
}

# 主函数
main() {
    check_requirements
    select_deployment_method
}

# 运行主函数
main

